<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\admin\model\User;
use think\Container;
use think\facade\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use Swoole\Server;
use think\swoole\Websocket;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Text;

class Index
{

    public function index()
    {

        $config = [
            'app_id' => 'wx7de8fb6893004a2b',
            'secret' => 'bdd23cae4292149313e6980d00f9fda2',

            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',
            'token' => 'TestToken',

            // 日志配置
            'log' => [
                'default' => 'dev', // 默认使用的 channel，生产环境可以改为下面的 prod
                'channels' => [
                    // 测试环境
                    'dev' => [
                        'driver' => 'single',
                        'path' => '/tmp/easywechat.log',
                        'level' => 'debug',
                    ],
                    // 生产环境
                    'prod' => [
                        'driver' => 'daily',
                        'path' => '/tmp/easywechat.log',
                        'level' => 'info',
                    ],
                ],
            ],
            //...
        ];

        $app = Factory::officialAccount($config);

        $app->server->push(function ($message) {
            // $message['FromUserName'] // 用户的 openid
            // $message['MsgType'] // 消息类型：event, text....
            switch ($message['MsgType']) {
                case 'text':
                    if ($message['Content'] == '模板消息'){


                    }
                    return new Text($message['Content']);
                default:
                    break;
            };


        });
        $response = $app->server->serve();

        // 将响应输出
        return $response;
    }


    public function test($message){
        $app->template_message->send([
            'touser' => 'user-openid',
            'template_id' => 'template-id',
            'url' => 'https://easywechat.org',
            'miniprogram' => [
                'appid' => 'xxxxxxx',
                'pagepath' => 'pages/xxx',
            ],
            'data' => [
                'key1' => 'VALUE',
                'key2' => 'VALUE2',
                ...
            ],
        ]);
    }
    public function login(Request $request)
    {
        //回复客户端消息
        $this->websocket->emit("testcallback", ['aaaaa' => 1]);
    }


}
